import { IComponent, IWindowSizeChange, IAfterViewInit } from './component';
import './webgl.less';
export abstract class WebGLComponent {
    protected canvasEle: HTMLCanvasElement;
    protected gl: WebGLRenderingContext;
    constructor(protected container: HTMLElement, id: any) {
        container.className = container.className + ' webgl-content';
        this.canvasEle = document.createElement('canvas') as HTMLCanvasElement;
        this.setSize()
        this.canvasEle.setAttribute('class', 'learn-webgl-cs');
        container.append(this.canvasEle);
        this.gl = this.canvasEle.getContext('webgl');
        // 创建fpo，缓冲区和背景一样大
    }
    public init() {

    }
    public afterviewInit() {
        this.renderWebGl();
    }
    public abstract renderWebGl(): void;
    public render(): HTMLElement {
        return null;
    }
    public windowSizeChange(ev: any) {
        this.setSize()
        // this.gl.viewport(0,0, width, height);
        this.container.append(this.canvasEle);
        this.renderWebGl();
    }
    protected setSize() {
        let height = this.container.clientHeight;
        let width = this.container.clientWidth;
        let min = width > height?height:width;
        min = parseInt((min * 0.95).toString());
        this.canvasEle.setAttribute('height', min.toString());
        this.canvasEle.setAttribute('width', min.toString());
        this.canvasEle.setAttribute('style', `height: ${min}px;width: ${min}px;`)
        this.canvasEle.setAttribute('class', 'learn-webgl-cs');
    }
    protected clear() {
        // 清除指定<画布>的颜色
        this.gl.clearColor(240/255, 240/255, 240/255, 1.0);

        // // 清空 <canvas>
        this.gl.clear(this.gl.COLOR_BUFFER_BIT);
    }

    protected createProgram(vs: string, fs: string):WebGLProgram {
        var vertShader = this.gl.createShader(this.gl.VERTEX_SHADER);
        this.gl.shaderSource(vertShader, vs);
        this.gl.compileShader(vertShader);
        if(!this.gl.getShaderParameter(vertShader, this.gl.COMPILE_STATUS)) {
            let err = this.gl.getShaderInfoLog(vertShader);
            console.log(err);
            console.log(this.gl.getShaderParameter(vertShader, this.gl.COMPILE_STATUS));
        }
        //编译着顶点/片段着色器
        var fragShader = this.gl.createShader(this.gl.FRAGMENT_SHADER);
        this.gl.shaderSource(fragShader, fs);
        this.gl.compileShader(fragShader);

        // 绑定并且启用 program
        var shaderProgram = this.gl.createProgram();
        this.gl.attachShader(shaderProgram, vertShader);
        this.gl.attachShader(shaderProgram, fragShader);
        this.gl.linkProgram(shaderProgram);
        this.gl.useProgram(shaderProgram);
        return shaderProgram;
    }
} 